﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Practices.Unity;

namespace Deixei.Infrastructure
{
    public class HttpContextDisposableLifetimeManager : LifetimeManager, IDisposable
    {
        //since this is a constant string, you can only instantiate one of these
        const string ItemName = "HttpContextLifetimeManager";

        public void DisposingHandler(object source, EventArgs e)
        {
            RemoveValue();
        }

        public override object GetValue()
        {
            return HttpContext.Current.Items[ItemName];
        }
        public override void RemoveValue()
        {
            Dispose();
            HttpContext.Current.Items.Remove(ItemName);
        }

        public override void SetValue(object newValue)
        {
            HttpContext.Current.Items[ItemName] = newValue;
        }
        public void Dispose()
        {
            var obj = (IDisposable)GetValue();
            obj.Dispose();
        }
    }

}
